package com.zsx.shopping.auth.service.impl;

import com.zsx.shopping.auth.converter.AuthConverter;
import com.zsx.shopping.auth.form.LoginForm;
import com.zsx.shopping.auth.service.LoginService;
import com.zsx.shopping.auth.service.VerifyService;
import com.zsx.shopping.common.api.R;
import com.zsx.shopping.common.api.user.dto.LoginDto;
import com.zsx.shopping.common.api.user.feign.UserFeignService;
import com.zsx.shopping.common.constant.ShoppingConstant;
import com.zsx.shopping.common.enums.CodeMsg;
import com.zsx.shopping.common.exception.ShoppingException;
import com.zsx.shopping.common.session.UserVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserFeignService userFeignService;

    @Resource
    private HttpServletRequest request;

    @Resource
    private VerifyService verifyService;

    @Resource
    private AuthConverter authConverter;

    @Override
    public void login(LoginForm loginForm) {
        verifyService.checkVerifyCode(loginForm.getCode());
        LoginDto loginDto = authConverter.toLoginDto(loginForm);
        R<UserVO> r = userFeignService.login(loginDto);
        if (!r.getCode().equals(CodeMsg.SUCCESS.getCode())) {
            throw new ShoppingException(r.getCode(), r.getMsg());
        }
        HttpSession session = request.getSession();
        session.setAttribute(ShoppingConstant.LOGIN_USER, r.getData());
    }

    @Override
    public void logout() {
        HttpSession session = request.getSession();
        session.removeAttribute(ShoppingConstant.LOGIN_USER);
    }

    @Override
    public UserVO getUser() {
        HttpSession session = request.getSession();
        return (UserVO) session.getAttribute(ShoppingConstant.LOGIN_USER);
    }
}
